import { getPublicKey } from "@/api/publicKey";
import { localGet } from "./util";
import { sm2 } from "sm-crypto";
/**
 * @description RSA加密(支持长字符加密)
 * @param data
 * @returns {Promise<{param: PromiseLike<ArrayBuffer>}|*>}
 */
export async function encryptedData(data: any) {
  let publicKey = localGet("publicKey");
  if (!publicKey) {
    const res = await getPublicKey();
    publicKey = res.data;
  }
  if (publicKey === "" || !data) {
    return data;
  }
  const result = sm2.doEncrypt(JSON.stringify(data), publicKey);
  return result;
}

/**
 * @description RSA解密(支持长字符解密)
 * @param data
 * @returns {PromiseLike<ArrayBuffer>}
 */
export async function decryptedData(data: string) {
  const res = await getPublicKey();
  const privateKey = res.data;
  if (privateKey === "") {
    return data;
  }
  const result = sm2.doDecrypt(data);
  return JSON.parse(result);
}
